package com.randi.monitor.service.impl;

import com.randi.common.utils.MathFloatUtils;
import com.randi.common.utils.ip.IpUtils;
import com.randi.monitor.dto.SysServer;
import com.randi.monitor.dto.service.*;
import com.randi.monitor.service.ISysServerService;
import org.springframework.stereotype.Service;
import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.CentralProcessor.TickType;
import oshi.hardware.GlobalMemory;
import oshi.software.os.FileSystem;
import oshi.software.os.OSFileStore;
import oshi.util.Util;

import java.util.List;
import java.util.Properties;

@Service
public class SysServerServiceImpl implements ISysServerService {

    /**
     * 等待1秒
     */
    private static final int SLEEP_WAIT_SECOND = 1000;

    /**
     * 设置服务器cpu信息
     *
     * @param cpu 服务器CPU信息
     */
    private void setServerCpuInfo(Cpu cpu) {
        CentralProcessor processor = new SystemInfo().getHardware().getProcessor();

        long[] prevTicks = processor.getSystemCpuLoadTicks();
        Util.sleep(SLEEP_WAIT_SECOND);
        long[] ticks = processor.getSystemCpuLoadTicks();
        long nice = ticks[TickType.NICE.getIndex()] - prevTicks[TickType.NICE.getIndex()];
        long irq = ticks[TickType.IRQ.getIndex()] - prevTicks[TickType.IRQ.getIndex()];
        long softIrq = ticks[TickType.SOFTIRQ.getIndex()] - prevTicks[TickType.SOFTIRQ.getIndex()];
        long steal = ticks[TickType.STEAL.getIndex()] - prevTicks[TickType.STEAL.getIndex()];
        long cSys = ticks[TickType.SYSTEM.getIndex()] - prevTicks[TickType.SYSTEM.getIndex()];
        long user = ticks[TickType.USER.getIndex()] - prevTicks[TickType.USER.getIndex()];
        long wait = ticks[TickType.IOWAIT.getIndex()] - prevTicks[TickType.IOWAIT.getIndex()];
        long free = ticks[TickType.IDLE.getIndex()] - prevTicks[TickType.IDLE.getIndex()];
        long totalCpu = user + nice + cSys + free + wait + irq + softIrq + steal;

        cpu.setCores(processor.getLogicalProcessorCount());
        cpu.setTotal(totalCpu);
        cpu.setSystem(cSys);
        cpu.setUsed(user);
        cpu.setWait(wait);
        cpu.setFree(free);
    }

    /**
     * 设置服务器内存信息
     *
     * @param memory 服务器内存信息
     */
    private void setServerMemoryInfo(Memory memory) {
        GlobalMemory globalMemory = new SystemInfo().getHardware().getMemory();
        memory.setTotal(globalMemory.getTotal());
        memory.setUsed(globalMemory.getTotal() - globalMemory.getAvailable());
        memory.setFree(globalMemory.getAvailable());
    }

    /**
     * 设置服务器JVM信息
     *
     * @param jvm 服务器JVM信息
     */
    private void setServerJvmInfo(Jvm jvm) {
        Properties props = System.getProperties();
        jvm.setTotal(Runtime.getRuntime().totalMemory());
        jvm.setMax(Runtime.getRuntime().maxMemory());
        jvm.setFree(Runtime.getRuntime().freeMemory());
        jvm.setVersion(props.getProperty("java.version"));
        jvm.setHome(props.getProperty("java.home"));
    }

    /**
     * 设置服务器磁盘信息
     *
     * @param disks 服务器磁盘信息
     */
    private void setServerDisksInfo(List<Disk> disks) {
        FileSystem fileSystem = new SystemInfo().getOperatingSystem().getFileSystem();
        List<OSFileStore> fileStores = fileSystem.getFileStores();
        for (OSFileStore fs : fileStores) {
            long free = fs.getUsableSpace();
            long total = fs.getTotalSpace();
            long used = total - free;

            Disk disk = new Disk();
            disk.setDirName(fs.getMount());
            disk.setTypeName(fs.getType());
            disk.setTypeName(fs.getName());
            disk.setTotal(convertFileSize(total));
            disk.setFree(convertFileSize(free));
            disk.setUsed(convertFileSize(used));
            disk.setUsage(MathFloatUtils.mul(MathFloatUtils.div(used, total, 4), 100));
            disks.add(disk);
        }
    }

    /**
     * 字节转换
     *
     * @param size 字节大小
     * @return 转换后值
     */
    private String convertFileSize(long size) {
        long kb = 1024;
        long mb = kb * 1024;
        long gb = mb * 1024;
        if (size >= gb) {
            return String.format("%.1f GB", (float) size / gb);
        } else if (size >= mb) {
            float f = (float) size / mb;
            return String.format(f > 100 ? "%.0f MB" : "%.1f MB", f);
        } else if (size >= kb) {
            float f = (float) size / kb;
            return String.format(f > 100 ? "%.0f KB" : "%.1f KB", f);
        } else {
            return String.format("%d B", size);
        }
    }

    /**
     * 设置服务器系统信息
     *
     * @param systemInfo 服务器系统信息
     */
    private void setServerSystemInfo(Sys systemInfo) {
        Properties props = System.getProperties();
        systemInfo.setOsName(props.getProperty("os.name"));
        systemInfo.setOsArch(props.getProperty("os.arch"));
        systemInfo.setUserDir(props.getProperty("user.dir"));
        systemInfo.setComputerName(IpUtils.getHostName());
        systemInfo.setComputerIp(IpUtils.getHostIp());
    }

    /**
     * 获取服务器信息
     *
     * @return 服务器信息
     */
    @Override
    public SysServer getInfo() {
        SysServer sysServer = new SysServer();
        setServerCpuInfo(sysServer.getCpu());
        setServerMemoryInfo(sysServer.getMemory());
        setServerJvmInfo(sysServer.getJvm());
        setServerDisksInfo(sysServer.getDisks());
        setServerSystemInfo(sysServer.getSystem());
        return sysServer;
    }

}
